package org.example.projecttwo.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.entity.Advertisement;
import org.example.projecttwo.service.IAdvertisementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/ads")
@Tag(name = "广告管理", description = "广告信息管理")

public class AdvertisementController {

    @Autowired
    private IAdvertisementService advertisementService;

    @GetMapping("/list")
    @Operation(summary = "分页查询广告列表", description = "分页查询广告列表，支持状态筛选 -- 广告管理")
    public Result<IPage<Advertisement>> listAds(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<Advertisement> page = new Page<>(current, size);
        IPage<Advertisement> result = advertisementService.pageByStatus(page, status, keyword);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取广告详情", description = "根据广告ID获取广告详情 -- 广告管理")
    public Result<Advertisement> getAd(@PathVariable Long id) {
        Advertisement ad = advertisementService.getById(id);
        return Result.success(ad);
    }

    @PostMapping
    @Operation(summary = "新增广告", description = "新增广告，默认状态为待上架 -- 广告管理")
    public Result<Advertisement> creatAd(@Valid @RequestBody Advertisement ad) {
        ad.setClickCount(0);
        ad.setStatus(1);
        advertisementService.save(ad);
        return Result.success(ad);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改广告", description = "修改广告信息 -- 广告管理")
    public Result<Advertisement> updateAd(@PathVariable Long id, @Valid @RequestBody Advertisement ad) {
        Advertisement existing = advertisementService.getById(id);
        if (existing == null) {
            return Result.error("广告不存在");
        }
        if (existing.getStatus() == 2) {
            return Result.error("已上架广告不可编辑，请先下架");
        }
        // 新序号不为空 && 新序号与原序号不同
        if (ad.getSortOrder() != null && !Objects.equals(ad.getSortOrder(), existing.getSortOrder())) {
            try {
                // 更新排序序号
                advertisementService.updateSingleSortOrder(id, ad.getSortOrder());
            } catch (Exception e) {
                return Result.error("排序调整失败" + e.getMessage());
            }
            // 重置排序序号
            ad.setSortOrder(null);
        }
        // 更新
        ad.setId(id);
        advertisementService.updateById(ad);
        // 获取更新后的数据
        Advertisement updateAd = advertisementService.getById(id);
        return Result.success(updateAd);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除广告", description = "根据广告ID删除广告 -- 广告管理")
    public Result<String> deleteAd(@PathVariable Long id) {
        advertisementService.removeById(id);
        return Result.success("删除成功");
    }

    @PutMapping("/{id}/publish")
    @Operation(summary = "上架广告", description = "将广告状态改为已上架 -- 广告管理")
    public Result<String> publishAd(@PathVariable Long id) {
        advertisementService.updateStatus(id, 2);
        return Result.success("上架成功");
    }

    @PutMapping("/{id}/unpublish")
    @Operation(summary = "下架广告", description = "将广告状态改为已下架 -- 广告管理")
    public Result<String> unpublishAd(@PathVariable Long id) {
        advertisementService.updateStatus(id, 3);
        return Result.success("下架成功");
    }

    @PostMapping("/batch-publish")
    @Operation(summary = "批量上架广告", description = "批量上架广告 -- 广告管理")
    public Result<String> barchPublish(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条广告");
        }
        advertisementService.batchUpdateStatus(ids, 2);
        return Result.success("批量上架成功,共" + ids.size() + "条");
    }

    @PostMapping("/batch-unpublish")
    @Operation(summary = "批量下架广告", description = "批量下架广告 -- 广告管理")
    public Result<String> batchUnpublish(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条广告");
        }
        advertisementService.batchUpdateStatus(ids, 3);
        return Result.success("批量下架成功,共" + ids.size() + "条");
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除广告", description = "批量删除广告 -- 广告管理")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条广告");
        }
        advertisementService.removeByIds(ids);
        return Result.success("批量删除成功,共" + ids.size() + "条");
    }

    @PostMapping("/update-sort")
    @Operation(summary = "保存拖拽排序结果", description = "保存广告拖拽排序结果 -- 广告管理")
    public Result<String> updateSort(@RequestBody List<Long> adIds) {
        if (adIds == null || adIds.isEmpty()) {
            return Result.error("排序列表不能为空");
        }
        advertisementService.updateSortOrder(adIds);
        return Result.success("排序更新成功");
    }

    @GetMapping("/published-count")
    @Operation(summary = "获取已上架广告数量", description = "统计已上架广告的数量 -- 广告管理")
    public Result<Integer> getPublishedCount() {
        int count = advertisementService.countPublishedAds();
        return Result.success(count);
    }

}